package authorizer

import (
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	"github.com/ory/ladon"
	"go.uber.org/zap"
)

type Authorizer struct {
	warden ladon.Warden
}

type AuthorizeResponse struct {
	Allowed bool   `json:"allowed"`
	Denied  bool   `json:"denied,omitempty"`
	Reason  string `json:"reason,omitempty"`
	Error   string `json:"error,omitempty"`
}

func NewAuthorizer(authorizationClient AuthorizationInterface) *Authorizer {
	return &Authorizer{
		warden: &ladon.Ladon{
			Manager:     NewPolicyManager(authorizationClient),
			AuditLogger: NewAuditLogger(authorizationClient),
		},
	}
}

func (a *Authorizer) Authorize(request *ladon.Request) *AuthorizeResponse {
	baseLog.Debugf("authorize request: %+v", zap.Any("request", request))

	if err := a.warden.IsAllowed(request); err != nil {
		return &AuthorizeResponse{
			Denied: true,
			Reason: err.Error(),
		}
	}

	return &AuthorizeResponse{
		Allowed: true,
	}
}
